package com.acooly.module.openapi.client.provider.yuejb.marshal;

import com.acooly.core.utils.Reflections;
import com.acooly.module.openapi.client.api.exception.ApiClientException;
import com.acooly.module.openapi.client.api.marshal.ApiMarshalSupport;
import com.acooly.module.openapi.client.api.marshal.ApiUnmarshal;
import com.acooly.module.openapi.client.api.message.MessageFactory;
import com.acooly.module.openapi.client.provider.yuejb.OpenAPIClientYueJBProperties;
import com.acooly.module.openapi.client.provider.yuejb.YueJBConstants;
import com.acooly.module.openapi.client.provider.yuejb.domain.YueJBNotify;
import com.acooly.module.openapi.client.provider.yuejb.message.YueJBLoanNotify;
import com.acooly.module.openapi.client.provider.yuejb.utils.DomainObject2Map;
import com.acooly.module.openapi.client.provider.yuejb.utils.SignUtils;
import com.acooly.module.safety.Safes;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.lang.reflect.Field;
import java.util.Map;
import java.util.Set;

/**
 * Created by ouwen@yiji.com} on 2017/11/7.
 */
@Slf4j
@Service
public class YueJBNotifyUnmarshal extends ApiMarshalSupport implements ApiUnmarshal<YueJBNotify, Map<String, String>> {

    @Resource(name = "yueJBMessageFactory")
    private MessageFactory messageFactory;
    @Autowired
    private OpenAPIClientYueJBProperties openAPIClientYueJBProperties;

    @Override
    public YueJBNotify unmarshal(Map<String, String> message, String serviceName) {
        YueJBLoanNotify notify;
        try {
            log.info("响应报文:{}",message);
            notify = (YueJBLoanNotify)messageFactory.getNotify(serviceName);
            Set<Field> fields = Reflections.getFields(notify.getClass());
            for (Field field : fields) {
                String  key = field.getName();
                Reflections.invokeSetter(notify, field.getName(), message.get(key));
            }
            try {
                String signature = notify.getSign();//渠道返回sign
                log.debug("响应签名:{}", signature);
                Map<String, String> requestData =  DomainObject2Map.tomap(notify);
                //签名
                String waitingForSign = SignUtils.buildWaitingForSign(requestData);
                log.debug("代签名字符串:{}", waitingForSign);
                Safes.getSigner(YueJBConstants.SIGN_TYPE).verify(waitingForSign,openAPIClientYueJBProperties.getSign(),signature);
            } catch (Exception e) {
                log.error("请求报文处理异常：" + e.getMessage());
                return null;
            }
        } catch (Exception e) {
            throw new ApiClientException("解析响应报文错误:" + e.getMessage());
        }
        return notify;
    }
}
